using EasyAdmin.Admin.Entity.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EasyAdmin.Admin.Application.Services.Impl
{
    public class SysRoleService : ISysRoleService
    {
        private readonly ISqlSugarClient _db;

        public SysRoleService(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<List<SysRole>> GetRoleListAsync(string keyword = null)
        {
            var query = _db.Queryable<SysRole>();
            
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(r => r.RoleName.Contains(keyword) || r.RoleCode.Contains(keyword));
            }

            return await query.OrderBy(r => r.Sort).ToListAsync();
        }

        public async Task<SysRole> GetRoleByIdAsync(int roleId)
        {
            return await _db.Queryable<SysRole>().FirstAsync(r => r.Id == roleId);
        }

        public async Task<(bool Success, string Message)> CreateRoleAsync(SysRole role)
        {
            // 检查角色名称是否已存在
            var exists = await _db.Queryable<SysRole>()
                .AnyAsync(r => r.RoleName == role.RoleName || r.RoleCode == role.RoleCode);

            if (exists)
                return (false, "角色名称或编码已存在");

            role.CreateTime = DateTime.Now;
            role.Status = 1;

            var result = await _db.Insertable(role).ExecuteCommandAsync() > 0;
            return (result, result ? "创建成功" : "创建失败");
        }

        public async Task<(bool Success, string Message)> UpdateRoleAsync(SysRole role)
        {
            // 检查角色是否存在
            var exists = await _db.Queryable<SysRole>().FirstAsync(r => r.Id == role.Id);
            if (exists == null)
                return (false, "角色不存在");

            // 检查是否为系统内置角色
            if (exists.IsSystem)
                return (false, "系统内置角色不能修改");

            // 检查角色名称是否与其他角色重复
            var nameExists = await _db.Queryable<SysRole>()
                .AnyAsync(r => r.Id != role.Id && (r.RoleName == role.RoleName || r.RoleCode == role.RoleCode));

            if (nameExists)
                return (false, "角色名称或编码已存在");

            role.UpdateTime = DateTime.Now;
            var result = await _db.Updateable(role)
                .IgnoreColumns(r => new { r.CreateTime, r.IsSystem })
                .ExecuteCommandAsync() > 0;

            return (result, result ? "更新成功" : "更新失败");
        }

        public async Task<(bool Success, string Message)> DeleteRoleAsync(int roleId)
        {
            // 检查是否为系统内置角色
            var role = await _db.Queryable<SysRole>().FirstAsync(r => r.Id == roleId);
            if (role?.IsSystem == true)
                return (false, "系统内置角色不能删除");

            var result = await _db.Deleteable<SysRole>()
                .Where(r => r.Id == roleId)
                .ExecuteCommandAsync() > 0;

            return (result, result ? "删除成功" : "删除失败");
        }

        public async Task<(bool Success, string Message)> SetRoleStatusAsync(int roleId, int status)
        {
            if (status != 0 && status != 1)
                return (false, "状态值无效");

            // 检查是否为系统内置角色
            var role = await _db.Queryable<SysRole>().FirstAsync(r => r.Id == roleId);
            if (role?.IsSystem == true)
                return (false, "系统内置角色状态不能修改");

            var result = await _db.Updateable<SysRole>()
                .SetColumns(r => new SysRole { Status = status, UpdateTime = DateTime.Now })
                .Where(r => r.Id == roleId)
                .ExecuteCommandAsync() > 0;

            return (result, result ? "设置成功" : "设置失败");
        }

        public async Task<(bool Success, string Message)> AssignPermissionsAsync(int roleId, List<int> menuIds)
        {
            // 这里需要实现角色-菜单关联表的处理逻辑
            // 由于菜单实体尚未创建，此处先返回成功
            return await Task.FromResult((true, "权限分配成功"));
        }

        public async Task<List<int>> GetRolePermissionsAsync(int roleId)
        {
            // 这里需要实现从角色-菜单关联表查询权限ID的逻辑
            // 由于菜单实体尚未创建，此处先返回空列表
            return await Task.FromResult(new List<int>());
        }
    }
}